package controllers

import (
	"fmt"
	"gitee.com/lidongyooo/goblog/app/models/user"
	"gitee.com/lidongyooo/goblog/app/requests"
	"gitee.com/lidongyooo/goblog/pkg/auth"
	"gitee.com/lidongyooo/goblog/pkg/flash"
	"gitee.com/lidongyooo/goblog/pkg/logger"
	"gitee.com/lidongyooo/goblog/pkg/route"
	"gitee.com/lidongyooo/goblog/pkg/view"
	"gorm.io/gorm"
	"net/http"
	"time"
)

type AuthController struct {
}

type userForm struct {
	Name					string `valid:"name"`
	Email					string `valid:"email"`
	Password				string `valid:"password"`
	PasswordConfirm			string `valid:"password_confirm"`
}

// Register 注册页面
func (*AuthController) Register(w http.ResponseWriter, r *http.Request) {
	view.RenderSimple(w, view.D{}, "auth.register")
}

// DoRegister 处理注册逻辑
func (*AuthController) DoRegister(w http.ResponseWriter, r *http.Request) {
	// 1. 初始化数据
	_user := user.User{
		Name:            r.PostFormValue("name"),
		Email:           r.PostFormValue("email"),
		Password:        r.PostFormValue("password"),
		PasswordConfirm: r.PostFormValue("password_confirm"),
	}
	errs := requests.ValidateRegistrationForm(_user)

	if len(errs) > 0 {
		// 3. 有错误发生，打印数据
		view.RenderSimple(w, view.D{
			"Errors": errs,
			"User": _user,
		}, "auth.register")
	} else {
		// 4. 验证成功，创建数据
		_user.Create()

		if _user.Id > 0 {
			flash.Success("注册成功，请查看邮箱激活账号")
			http.Redirect(w, r, "/", http.StatusFound)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "注册失败，请联系管理员")
		}
	}
}

func (*AuthController) Login(w http.ResponseWriter, r *http.Request) {
	view.RenderSimple(w, view.D{}, "auth.login")
}

// DoLogin 处理登录表单提交
func (*AuthController) DoLogin(w http.ResponseWriter, r *http.Request) {
	email := r.PostFormValue("email")
	password := r.PostFormValue("password")

	// 2. 尝试登录
	if err := auth.Attempt(email, password); err == nil {
		if auth.User().Activated != 1 {
			auth.Logout()
			view.RenderSimple(w, view.D{
				"Error":    "你的账号未激活，请检查邮箱中的注册邮件进行激活。",
				"Email":    email,
				"Password": password,
			}, "auth.login")
		} else {
			flash.Success("欢迎回来！")
			// 登录成功
			http.Redirect(w, r, "/", http.StatusFound)
		}
	} else {
		// 3. 失败，显示错误提示
		view.RenderSimple(w, view.D{
			"Error":    err.Error(),
			"Email":    email,
			"Password": password,
		}, "auth.login")
	}
}

func (*AuthController) Logout(w http.ResponseWriter, r *http.Request) {
	auth.Logout()
	flash.Success("您已退出登录")
	http.Redirect(w, r, "/", http.StatusFound)
}

func (*AuthController) ConfirmEmail(w http.ResponseWriter, r *http.Request) {
	token := route.GetRouteVariable("token", r)

	user, err := user.GetByActivationToken(token)

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, "404 未找到相关用户")
		} else {
			logger.LogError(err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "500 服务器内部错误")
		}
	}

	user.Activated = 1
	user.ActivationToken = ""
	now := time.Now()
	user.EmailVerifiedAt = &now

	rowsAffected, err := user.Update()

	if err != nil {
		// 数据库错误
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprint(w, "500 服务器内部错误")
		return
	}

	if rowsAffected > 0 {
		auth.Login(user)
		flash.Success("账户激活完成")
		http.Redirect(w, r, "/", http.StatusFound)
	} else {
		fmt.Fprint(w, "What happened?")
	}
}